package com.adopapa.ethexplorer.conf;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;

import reactor.core.publisher.Mono;

/**
 * 拦截器
 */
@Component
@Order(100)
public class DAuthFilter implements WebFilter {
	
	@Autowired
	private AppConfig appConfig;

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
		logger.info("filter auth request ");
		ServerHttpRequest request = exchange.getRequest();
		// ServerHttpResponse response = exchange.getResponse();
//		boolean debug = true;
//		if (debug) {
//			return chain.filter(exchange);
//		}
		String path = request.getURI().getPath();
		logger.info(path);
		logger.info(request.getHeaders().toSingleValueMap().toString());
		
		if (path.indexOf("/health/") >= 0 //
				|| path.indexOf("/api-docs") >= 0) {
			return chain.filter(exchange);
		}

		String loginToken = request.getHeaders().getFirst("authorization");
		logger.info(loginToken);
		
		return chain.filter(exchange);
		
//		if (!Tools.empty(loginToken) && appConfig.getApiToken().equals(loginToken)) {
//			return chain.filter(exchange);
//		}
//		else {
//			/*
//			 * http头中没有appKey，修改请求的目标url为/auth/error request.mutate返回一个请求构建器(builder design
//			 * pattern)，path方法修改请求的url，build方法返回新的request
//			 */
//			ServerHttpRequest authErrorRequest = request.mutate().path("/debugrecord/auth/error").build();
//			// erverWebExchange.mutate类似，构建一个新的ServerWebExchange
//			ServerWebExchange authErrorExchange = exchange.mutate().request(authErrorRequest).build();
//			return chain.filter(authErrorExchange);
//		}

	}

}
